package com.ljkj.cordial.chat.presenter;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.sp.SPKeys;
import com.lanjiu.lib.utils.sp.SharedPreferenceHelper;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.activity.FileDownloadActivity;
import com.ljkj.cordial.chat.adapter.ChatAdapter;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.ChatTableUnit;
import com.ljkj.cordial.chat.bean.PayLoad;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.SpeechVoiceUtil;
import com.ljkj.cordial.chat.widget.CommonHintDialog;
import com.nic.view.util.AndroidFileUtil;
import com.nic.view.util.FileSizeUtil;
import com.nic.view.widget.CircleImageView;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 附件
 */
public class FilePresenter extends AChatPresenter {


    public FilePresenter(int direction) {
        super(direction);
//        LayoutInflater.from(view.getContext()).inflate(R.layout.item_chat_right_file, null);
    }

    @Override
    public RecyclerView.ViewHolder getViewHolder(View view) {
        if (getDirection() == LEFT) {
            return new ViewLeftHolder(view);
        }
        return new ViewRightHolder(view);
    }

    @Override
    public void bindViewHolder(RecyclerView.ViewHolder holder, Object obj, int position) {
        ChatTableUnit item = (ChatTableUnit) obj;
        Context context = holder.itemView.getContext();
        if (getDirection() == LEFT) {
            int drawableId = AlbumTableBean.getMineType(false, item.getFileUrl());
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewLeftHolder.llPhotoMsg.getLayoutParams();
            if (getChatType() == Canstants.SINGLE_CHAT) {
                viewLeftHolder.tvTitle.setVisibility(View.GONE);
                params.topMargin = context.getResources().getDimensionPixelOffset(R.dimen.dimen_8);
                viewLeftHolder.llPhotoMsg.setLayoutParams(params);
            } else {
                viewLeftHolder.tvTitle.setText(TextUtils.isEmpty(item.getAlias()) ? item.getTargetName() : item.getAlias());
            }
            setVisible(viewLeftHolder.cb, item.isVisible());
            setCheck(viewLeftHolder.cb, item.isChecked());
            viewLeftHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }

                }
            });

            viewLeftHolder.llPhotoMsg.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            viewLeftHolder.ivFileImg.setImageResource(drawableId);
            viewLeftHolder.tvFileName.setText(getFileName(item.getFileUrl(), "\\"));
            String size = getFileSize(item.getFileLength());
            if ("0.00B".equals(size) || "0.0B".equals(size) || "0B".equals(size)) {
                viewLeftHolder.tvFileSize.setText("");
            } else {
                viewLeftHolder.tvFileSize.setText(size);
            }
            viewLeftHolder.ivIsVisitor.setVisibility(IMSContacts.UserType.TOURISTS_USER.equals(item.getTargetType()) ? View.VISIBLE : View.GONE);
            loadAvatar(item, viewLeftHolder.ivAvatar);
            setReadFinishState(viewLeftHolder.tvDownTime, item.isStartReadFinish());
            resultFile(item.getId(), viewLeftHolder.llPhotoMsg);
        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            setVisible(viewRightHolder.cb, item.isVisible());
            if (item.isVisible()) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.addRule(RelativeLayout.LEFT_OF, viewRightHolder.cb.getId());
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_48);
            } else {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRightHolder.ivAvatar.getLayoutParams();
                params.rightMargin = viewRightHolder.cb.getContext().getResources().getDimensionPixelOffset(R.dimen.dimen_16);
            }
            setCheck(viewRightHolder.cb, item.isChecked());
            viewRightHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    item.setChecked(isChecked);
                    if (getOnCListener() != null) {
                        getOnCListener().onItemCheckChange(buttonView, item, position, isChecked);
                    }
                }
            });

            viewRightHolder.ivFail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemReloadClick(v, item, position);
                    }
                }
            });
            viewRightHolder.llPhotoMsg.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (getOnCListener() != null) {
                        getOnCListener().onItemLongClick(v, item, position);
                        return true;
                    }
                    return false;
                }
            });
            String pathC = getPath(item);
            int drawableId = AlbumTableBean.getMineType(true, pathC);
            viewRightHolder.ivFileImg.setImageResource(drawableId);
            String size = getFileSize(pathC);
            if ("0.00B".equals(size) || "0.0B".equals(size) || "0B".equals(size)) {
                viewRightHolder.tvFileSize.setVisibility(View.GONE);
            } else {
                viewRightHolder.tvFileSize.setVisibility(View.VISIBLE);
                viewRightHolder.tvFileSize.setText(size);
            }

            viewRightHolder.tvFileName.setText(getFileName(pathC, "/"));
            refreshSendState(item, viewRightHolder.chatItemProgress, viewRightHolder.ivFail, viewRightHolder.tvDownTime);
            loadAvatar(item, viewRightHolder.ivAvatar);
            if (!TextUtils.isEmpty(pathC)) {
                viewRightHolder.llPhotoMsg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlbumManageUtil.getInstance().stopVoice();
                        setItemClick(pathC, viewRightHolder.llPhotoMsg.getContext());
                    }
                });

            }

        }
    }

    private void resultFile(Long chatId, View view) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (R.id.ll_photo_msg == v.getId())
                    AlbumManageUtil.getInstance().stopVoice();
                ChatTableBean msg = ChatTableBean.getTableFromId(String.valueOf(chatId));
                if (!TextUtils.isEmpty(msg.getAlbumId()) && Long.parseLong(msg.getAlbumId()) > 0) {
                    AlbumTableBean f = AlbumTableBean.queryById(Long.valueOf(msg.getAlbumId()));
                    if (f != null && !TextUtils.isEmpty(f.getMPath())) {
                        setItemClick(f.getMPath(), v.getContext());
                    } else {
                        FileDownloadActivity.jumpTo(v.getContext(), chatId);
                    }
                } else {
                    FileDownloadActivity.jumpTo(v.getContext(), chatId);
                }
            }
        });


    }

    public void setItemClick(String path, Context context) {

        if (!TextUtils.isEmpty(path)) {
            int mineType = AlbumTableBean.getFileType(path);
            if (AlbumTableBean.TYPE_VIDEO == mineType) {
                //                        VideoPlayActivity.jumpTo(context, item.getPath(), null);
                Intent intent = AndroidFileUtil.openFile(path);
                if (intent != null) {
                    context.startActivity(intent);
                    SpeechVoiceUtil.setAudioMute(context, false);
                }
            } else if (AlbumTableBean.TYPE_IMAGE == mineType) {
                AlbumManageUtil
                        .getInstance().lookLargePhoto(context, path);
            } else if (AlbumTableBean.TYPE_RECORD_FILE == mineType || AlbumTableBean.isRecordFile(path)) {
                String key = SPKeys.Key.CONFIG_VOICE_PLAY_BY_MAC + UserPreferences.getUserId();
                boolean isMac = SharedPreferenceHelper.create(SPKeys.Name.CONFIG).getBoolean(key, Canstants.DEFAULT_MAC);
                AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                if (am != null) {
                    am.setSpeakerphoneOn(!isMac);
                    am.setMode(isMac ? AudioManager.MODE_IN_CALL : AudioManager.MODE_NORMAL);
                }
                AlbumManageUtil.getInstance().playVoice(path, isMac, new AlbumManageUtil.OnPlayAnimListener() {
                    @Override
                    public void onStartAnim() {
                    }

                    @Override
                    public void onStopAnim() {
                    }
                });
                new CommonHintDialog(context).setContent(path).setSingleSubmitGray("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlbumManageUtil.getInstance().stopVoice();
                    }
                }).show();
            } else {
                Intent intent = AndroidFileUtil.openFile(path);
                if (intent != null) {
                    context.startActivity(intent);
                }
            }
        }
    }

    @Override
    public void bindViewHolder(ChatAdapter chatAdapter, int position, RecyclerView.ViewHolder holder, Object obj, PayLoad payLoad) {
        super.bindViewHolder(chatAdapter, position, holder, obj, payLoad);
        ChatTableUnit item = (ChatTableUnit) obj;
        if (getDirection() == LEFT) {
            ViewLeftHolder viewLeftHolder = (ViewLeftHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type)
                    loadAvatar(item, viewLeftHolder.ivAvatar);
                if (PayLoad.DOWN_TIME == type) {
                    if (item.isStartReadFinish()) {
                        viewLeftHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }
            }

        } else {
            ViewRightHolder viewRightHolder = (ViewRightHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.AVATAR == type)
                    loadAvatar(item, viewRightHolder.ivAvatar);
                if (item.getSendState() == ChatTableUnit.SEND_SUCCESS && PayLoad.DOWN_TIME == type) {
                    if (item.isStartReadFinish()) {
                        viewRightHolder.tvDownTime.setText(item.getReadFinishFormatTime());
                    }
                }
                if (PayLoad.REQ_STATE == type) {
                    refreshSendState(item, viewRightHolder.chatItemProgress, viewRightHolder.ivFail, viewRightHolder.tvDownTime);
                }
            }
        }

    }

    private String getFileName(String path, String suffix) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        if (path.contains(suffix)) {
            String name = path.substring(path.lastIndexOf(suffix) + 1, path.length());
            if (name.contains(".")) {
                String endxx = name.substring(name.lastIndexOf("."), name.length());
                String stxx = name.substring(0, name.lastIndexOf("."));
                if (stxx.length() > 12) {
                    stxx = stxx.substring(0, 12) + "..";
                }
                return stxx + endxx;
            }
            return path.substring(path.lastIndexOf("/") + 1, path.length());
        }
        return path;
    }


    private String getFileSize(String path) {
        if (TextUtils.isEmpty(path)) {
            return 0 + "B";
        }
        if (0.0f != FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_MB)) {
            return FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_MB) + "M";
        } else if (0.0f != FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_KB)) {
            return FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_KB) + "KB";
        } else if (0.0f != FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_B)) {
            return FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_B) + "B";
        }
        return 0 + "B";
    }

    private String getPath(ChatTableUnit item) {
        if (TextUtils.isEmpty(item.getAlbumId())) {
            return "";
        }
        String path = null;
        try {
            AlbumTableBean f = AlbumTableBean.queryById(Long.parseLong(item.getAlbumId()));
            path = f != null ? f.getMPath() : null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    public String getFileSize(Long length) {
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        if (length >= 1048576) {
            return df.format((double) length / 1048576) + "MB";
        } else if (length >= 1024) {
            return df.format((double) length / 1024) + "KB";
        } else if (length < 1024) {
            return df.format((double) length) + "B";
        } else {
            return "0B";
        }
    }


//    private void showFile(ViewLeftHolder viewLeftHolder, ChatTableUnit item, int position) {
//        Activity activity = (Activity) viewLeftHolder.itemView.getContext();
//        if (!TextUtils.isEmpty(item.getAlbumId()) && Long.parseLong(item.getAlbumId()) > 0) {
//            AlbumTableBean al = AlbumTableBean.queryById(Long.parseLong(item.getAlbumId()));
//            if (al != null && !TextUtils.isEmpty(al.getMPath())) {
//                viewLeftHolder.chatItemProgress.hide();
//            }
//            resultLeftFile(viewLeftHolder, item, position);
//        } else {
//            if (viewLeftHolder.chatItemProgress.isShown()) {
//                return;
//            }
//            viewLeftHolder.chatItemProgress.show();
//            if (Canstants.SINGLE_CHAT == item.getFromType())
//                AlbumManageUtil.getInstance().downLoadFileFriend(item.getFileUrl(), AlbumTableBean.TYPE_EXTRA_FILE, item.getTargetId(), new AlbumManageUtil.OnFileResponse() {
//                    @Override
//                    public void onProgress(int progress) {
//                        super.onProgress(progress);
//                        if (activity == null || activity.isFinishing()) {
//                            return;
//                        }
//                        viewLeftHolder.chatItemProgress.setProgress(progress);
//                    }
//
//                    @Override
//                    public void onResult(String path, String fileId) {
//                        if (activity == null || activity.isFinishing()) {
//                            return;
//                        }
//                        resultFile(fileId, viewLeftHolder, item, position);
//
//                    }
//                });
//            else
//                AlbumManageUtil.getInstance().downLoadFileGroupMember(item.getFileUrl(), AlbumTableBean.TYPE_EXTRA_FILE
//                        , item.getGroupType(), item.getGroupId(), item.getTargetType(), item.getTargetId(), new AlbumManageUtil.OnFileResponse() {
//                            @Override
//                            public void onProgress(int progress) {
//                                super.onProgress(progress);
//                                if (activity == null || activity.isFinishing()) {
//                                    return;
//                                }
//                                viewLeftHolder.chatItemProgress.setProgress(progress);
//                            }
//
//                            @Override
//                            public void onResult(String url, String fileId) {
//                                if (activity == null || activity.isFinishing()) {
//                                    return;
//                                }
//                                resultFile(fileId, viewLeftHolder, item, position);
//                            }
//                        });
//        }
//
//    }

//    private void resultFile(String fileId, ViewLeftHolder viewLeftHolder, ChatTableUnit item, int position) {
//        viewLeftHolder.chatItemProgress.hide();
//        if (!TextUtils.isEmpty(fileId) && Long.parseLong(fileId) > 0) {
//            item.setAlbumId(fileId);
//            ChatTableUnit.update(item);
//        }
////        String pathC = getPath(item);
////        int drawableId = getMineType(pathC);
////        viewLeftHolder.tvFileName.setText(getFileName(pathC));
////        viewLeftHolder.ivFileImg.setImageResource(drawableId);
////        viewLeftHolder.tvFileSize.setText(getFileSize(pathC));
//        if (loadFinishListener != null) {
//            loadFinishListener.onFinish();
//        }
//
//    }
//
//    private void resultLeftFile(ViewLeftHolder viewLeftHolder, ChatTableUnit item, int position) {
//        viewLeftHolder.chatItemProgress.hide();
////        String pathC = getPath(item);
////        int drawableId = getMineType(pathC);
////        viewLeftHolder.tvFileName.setText(getFileName(pathC));
////        viewLeftHolder.ivFileImg.setImageResource(drawableId);
////        viewLeftHolder.tvFileSize.setText(getFileSize(pathC));
//        if (loadFinishListener != null) {
//            loadFinishListener.onFinish();
//        }
//    }

    public static class ViewLeftHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.iv_is_visitor)
        ImageView ivIsVisitor;
        @BindView(R.id.ll_avatar)
        FrameLayout llAvatar;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.tv_fileName)
        TextView tvFileName;
        @BindView(R.id.ll_photo_msg)
        CardView llPhotoMsg;
        @BindView(R.id.iv_file_img)
        ImageView ivFileImg;
        @BindView(R.id.tv_fileSize)
        TextView tvFileSize;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;
        @BindView(R.id.chat_item_progress)
        ContentLoadingProgressBar chatItemProgress;

        ViewLeftHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            AChatPresenter.setProgressColor(chatItemProgress);
//            setIsRecyclable(false);
        }
    }

    public static class ViewRightHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cb)
        CheckBox cb;
        @BindView(R.id.iv_avatar)
        CircleImageView ivAvatar;
        @BindView(R.id.tv_fileName)
        TextView tvFileName;
        @BindView(R.id.ll_photo_msg)
        CardView llPhotoMsg;
        @BindView(R.id.iv_fail)
        ImageView ivFail;
        @BindView(R.id.chat_item_progress)
        ContentLoadingProgressBar chatItemProgress;
        @BindView(R.id.iv_file_img)
        ImageView ivFileImg;
        @BindView(R.id.tv_fileSize)
        TextView tvFileSize;
        @BindView(R.id.tv_downTime)
        TextView tvDownTime;

        ViewRightHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            AChatPresenter.setProgressColor(chatItemProgress);
//            setIsRecyclable(false);
        }
    }

    private OnAnnexLoadFinishListener loadFinishListener;

    public void setLoadFinishListener(OnAnnexLoadFinishListener loadFinishListener) {
        this.loadFinishListener = loadFinishListener;
    }

    public interface OnAnnexLoadFinishListener {
        void onFinish();
    }
}
